<template>
   <!-- 新增出库单 -->
   <div class="dialog-box">
      <el-dialog v-model="dialogVisible" :title="dialogTitle"  width="90%" max-width="1200px">
         <el-form :model="form" label-width="100px">
            <!-- 客户 -->
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="客户" required>
                     <el-input v-model="form.customer_name" placeholder="请选择" suffix-icon="MoreFilled"
                        @focus="openSelectCustomersPopup" readonly />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="联系电话" required>
                     <el-input disabled v-model="form.customer_phone" placeholder="根据所选客户带出" readonly />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="收货地址" required>
                     <!-- 地区级联选择器 -->
                     <el-cascader v-model="form.regionValue" :options="regionOptions" :props="cascaderProps"
                        placeholder="请选择省市区" @change="handleRegionChange" clearable style="width: 100%" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="详细地址" required>
                     <el-input disabled v-model="form.address" placeholder="请输入详细地址" />
                  </el-form-item>
               </el-col>
            </el-row>
            <!-- 出库负责人 -->
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="出库负责人" required>
                     <el-input v-model="form.org_member_name" placeholder="请选择" suffix-icon="MoreFilled"
                        @focus="openOutboundOrderManagerPopup" readonly />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="负责人电话" required>
                     <el-input disabled v-model="form.org_member_phone" placeholder="根据所选负责人带出" readonly />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="出库日期" required>
                     <!-- 精确到日例如2025-01-01 -->
                     <el-date-picker type="date" placeholder="请选择出库日期" v-model="form.order_date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" style="width: 100%" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="交货日期" required>
                     <!-- 精确到日例如2025-01-01 -->
                     <el-date-picker type="date" placeholder="请选择交货日期" v-model="form.delivery_date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" style="width: 100%" :disabled-date="disabledDate" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-form-item label="备注">
               <el-input v-model="form.note" placeholder="请输入" />
            </el-form-item>

            <div class="supply-products" v-if="form.type !== 2">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     出库产品
                  </div>
                  <!-- 需要有客户id才能点击 -->
                  <el-button @click="openSelectProductsPopup" :disabled="!form.customer_id"> 选择产品 </el-button>
               </div>
               <!-- 产品列表信息由选择产品弹窗带出，其中的出库数量，出库单价，折扣，由自己填写其他的要么带出要么算 -->
               <div class="table-box">
               <el-table border :data="form.product_data" style="width: 100%"  :max-height="tableMaxHeight">
                  <el-table-column prop="name" label="产品名称" width="auto" />
                  <el-table-column prop="no" label="产品编号" width="auto" />
                  <el-table-column prop="specification" label="规格型号" width="auto" />
                  <el-table-column prop="measure_unit_name" label="采购单位" width="auto" />
                  <el-table-column prop="open_unit_name" label="拆零" width="auto">
                     <template #default="scope">
                        <!-- 字符串拼接一下 -->
                        <span>{{ scope.row.open_unit_num + scope.row.open_unit_name }}</span>

                     </template>
                  </el-table-column>
                  <el-table-column prop="spu_measure_unit_name" label="规格单位" width="auto" />
                  <el-table-column label="出库数量" width="120">
                     <template #default="scope">
                        <!-- 初始化的时候为0 -->
                        <el-input v-model="scope.row.num" placeholder="请输入" type="number" max="999999999" min="1"
                           @input="handleOutboundNumChange(scope.row)" 
                           @change="handleOutboundNumChange(scope.row)" />
                     </template>
                  </el-table-column>

                  <!-- 新增：出库量列 -->
                  <el-table-column label="出库量" width="120">
                     <template #default="scope">
                        <!-- 使用统一的显示函数 -->
                        <span>{{ getOutboundVolumeDisplay(scope.row) }}</span>
                     </template>
                  </el-table-column>

                  <el-table-column label="供应商" width="auto">
                     <template #default="scope">
                        <span v-if="scope.row.suppliers && scope.row.suppliers.length > 0">
                           {{scope.row.suppliers.map(item => item.name).join(', ')}}
                        </span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                     <template #default="scope">
                        <el-button type="danger" link @click="handleRemoveProduct(scope.row)">移除</el-button>
                     </template>
                  </el-table-column>
               </el-table>
               </div>
            </div>

            <div class="supply-products" v-if="form.id && form.type !== 1 && restockProductsData.length > 0">
               <div class="title">
                  <div class="title-text">
                     <div class="line"></div>
                     补库产品
                  </div>
               </div>
               <!-- 补库产品树形表格 -->
               <div class="table-box">
               <el-table border :data="restockProductsData" style="width: 100%" row-key="id"  :max-height="tableMaxHeight"
                  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :expand-row-keys="expandedRows"
                  @expand-change="handleExpandChange">

                  <!-- 产品名称SPU -->
                  <el-table-column prop="spu_name" label="产品名称SPU" width="200">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'category'" class="category-name">
                           <el-icon class="category-icon">
                              <FolderOpened />
                           </el-icon>
                           {{ scope.row.spu_name || scope.row.name || scope.row.category }}
                        </span>
                        <span v-else>{{ scope.row.name }}</span>
                     </template>
                  </el-table-column>

                  <!-- 产品名称 -->
                  <el-table-column prop="name" label="产品名称" width="150">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">{{ scope.row.name }}</span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 采购单位 -->
                  <el-table-column prop="unit" label="采购单位" width="100">

                  </el-table-column>

                  <!-- 库存数量 -->
                  <el-table-column prop="stock" label="库存数量" width="100">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">{{ scope.row.stock }}</span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 出库数量 -->
                  <el-table-column prop="num" label="出库数量" width="120">
                     <template #default="scope">
                        <el-input v-if="scope.row.type === 'product'" v-model="scope.row.num" placeholder="请输入"
                           type="number" :min="0" size="small" 
                           @input="handleOutboundNumChange(scope.row)" 
                           @change="handleOutboundNumChange(scope.row)" />
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 拆零 -->
                  <el-table-column prop="discount" label="拆零" width="80">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">{{ scope.row.open_unit_num + scope.row.open_unit_name
                        }}</span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 规格型号 -->
                  <el-table-column prop="specification" label="规格型号" width="120">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">{{ scope.row.specification || scope.row.rules || '-'
                           }}</span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 待出库 -->
                  <el-table-column prop="pending_outbound" label="待出库" width="100">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'category'"
                           :style="{ color: getCategoryStockColor(scope.row.pending_outbound), fontWeight: 'bold' }">
                           <!-- 直接显示计算好的待出库总量 -->
                           {{ scope.row.pending_outbound_display || '0' }}
                        </span>
                        <!-- **核心修正：产品行不显示待出库数据** -->
                        <span v-else-if="scope.row.type === 'product'">-</span>
                     </template>
                  </el-table-column>

                  <!-- 出库量 -->
                  <el-table-column prop="outbound_volume" label="出库量" width="100">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">
                           <!-- 使用统一的显示函数 -->
                           {{ getOutboundVolumeDisplay(scope.row) }}
                        </span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 供应商 -->
                  <el-table-column prop="supplier" label="供应商" width="120">
                     <template #default="scope">
                        <span v-if="scope.row.type === 'product'">
                           {{ scope.row.supplier || (scope.row.suppliers && scope.row.suppliers.length > 0 ?
                              scope.row.suppliers[0].name : '-') }}
                        </span>
                        <span v-else>-</span>
                     </template>
                  </el-table-column>

                  <!-- 操作 -->
                  <el-table-column label="操作" width="120" fixed="right">
                     <template #default="scope">
                        <el-button v-if="scope.row.type === 'category'" type="primary" link
                           @click="openSelectRestockProductsPopup(scope.row)">
                           选择产品
                        </el-button>
                        <el-button v-else-if="scope.row.type === 'product'" type="danger" link
                           @click="handleRemoveRestockProduct(scope.row, findParentCategory(scope.row))">
                           移除
                        </el-button>
                     </template>
                  </el-table-column>
               </el-table>
               </div>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">

               <el-button @click="closeDialog">取消</el-button>
               <el-button color="#626aef" @click="handleSubmit">
                  确定
               </el-button>
            </div>
         </template>
      </el-dialog>
      <!-- 选择客户 -->
      <SelectCustomers ref="selectCustomersRef" @selectCustomer="handleSelectCustomer" />
      <!-- 选择出库负责人 -->
      <OutboundOrderManager ref="outboundOrderManagerRef"
         @selectOutboundOrderManager="handleSelectOutboundOrderManager" />
      <!-- 选择产品 -->
      <SelectProduct ref="selectProductsRef" @selectProduct="handleSelectProduct" />
   </div>
</template>

<script setup lang="ts">
import api from "@/api";
import { ref, reactive, computed, watch, onMounted } from "vue";
import SelectCustomers from "./SelectCustomers.vue";//选择客户
import OutboundOrderManager from "./OutboundOrderManager.vue";//选择出库负责人
import SelectProduct from "./SelectProduct.vue";//选择产品
import { ElMessage } from "element-plus";
import { FolderOpened } from "@element-plus/icons-vue";
import regionData from "@/utils/regionData.js"; // 导入地区数据

// ------------打开弹窗------------
const selectCustomersRef = ref<any>(null); // 选择客户弹窗
const outboundOrderManagerRef = ref<any>(null); // 选择出库负责人弹窗
const selectProductsRef = ref<any>(null); // 选择产品弹窗
const dialogVisible = ref<boolean>(false); // 弹窗控制器

// 树形表格展开行控制
const expandedRows = ref<number[]>([]); // 保留这个声明，移除下面重复的

// 处理展开变化
const handleExpandChange = (row: any, expandedRowsParam: any[]) => {
   console.log('展开状态变化:', row, expandedRowsParam);
};

// 查找产品的父类别
const findParentCategory = (product: any) => {
   for (const category of restockProductsData.value) {
      if (category.children && category.children.some((child: any) => child.id === product.id)) {
         return category;
      }
   }
   return null;
};


// 地区数据配置
const regionOptions = ref<any[]>([]);
const cascaderProps = {
   value: 'code',
   label: 'name',
   children: 'children', // 直接使用children字段
   emitPath: true,
   checkStrictly: false
};

// ------------表单数据------------
const form = ref<any>({
   id: "",//订单id
   customer_id: "",//客户id
   customer_name: "",//客户名称
   customer_phone: "",//客户电话
   province: "", // 省份名称
   city: "", // 城市名称
   area: "", // 区域名称
   provinceCode: "", // 省份编码
   cityCode: "", // 城市编码
   areaCode: "", // 区域编码
   regionValue: [], // 级联选择器的值
   address: "",
   org_member_id: "",
   org_member_name: "",
   org_member_phone: "",
   order_date: "",
   delivery_date: "",
   note: "",
   product_data: [],//产品信息
   orderDiscount: 0, // 整单折扣
   finalAmount: 0, // 最终成交额
   status: 0, // 状态
   type: 0, // 类型
   warehouse_id: "", // 仓库ID
});

// 加载地区数据
const loadRegionData = () => {
   try {
      console.log('开始加载地区数据');

      // 转换数据结构，统一使用children字段
      const processedData = regionData.map((province: any) => {
         return {
            ...province,
            // 将city字段重命名为children，以匹配级联选择器的配置
            children: province.city ? province.city.map((city: any) => {
               return {
                  ...city,
                  // 市级的children字段保持不变（指向区县）
                  children: city.children || []
               };
            }) : []
         };
      });

      regionOptions.value = processedData;
      console.log('地区数据加载成功，处理后的数据结构:', {
         provinces: regionOptions.value.length,
         firstProvince: regionOptions.value[0],
         firstCity: regionOptions.value[0]?.children?.[0],
         firstArea: regionOptions.value[0]?.children?.[0]?.children?.[0]
      });
   } catch (error) {
      console.error('地区数据加载失败:', error);
      regionOptions.value = [];
   }
};

// 组件挂载时加载地区数据
onMounted(() => {
   loadRegionData();
});

const tableMaxHeight = computed(() => {
  return window.innerHeight - 600; // 留出标题、按钮、表头等空间
});

// 地区级联选择处理
const handleRegionChange = (value: string[]) => {
   console.log('地区选择变化:', value);

   if (!value || value.length === 0) {
      // 清空选择
      form.value.province = '';
      form.value.city = '';
      form.value.area = '';
      form.value.provinceCode = '';
      form.value.cityCode = '';
      form.value.areaCode = '';
      return;
   }

   try {
      // 现在value是完整路径数组 [provinceCode, cityCode, areaCode]
      const selectedCodes = Array.isArray(value) ? value : [value];

      if (selectedCodes.length >= 1) {
         // 查找省份
         const province = regionOptions.value.find(p => p.code === selectedCodes[0]);
         if (province) {
            form.value.province = province.name;
            form.value.provinceCode = province.code;
            console.log('选中省份:', province.name);
         }
      }

      if (selectedCodes.length >= 2) {
         // 查找城市 (现在在children字段中)
         const province = regionOptions.value.find(p => p.code === selectedCodes[0]);
         if (province && province.children) {
            const city = province.children.find((c: any) => c.code === selectedCodes[1]);
            if (city) {
               form.value.city = city.name;
               form.value.cityCode = city.code;
               console.log('选中城市:', city.name);
            }
         }
      }

      if (selectedCodes.length >= 3) {
         // 查找区域
         const province = regionOptions.value.find(p => p.code === selectedCodes[0]);
         if (province && province.children) {
            const city = province.children.find((c: any) => c.code === selectedCodes[1]);
            if (city && city.children) {
               const area = city.children.find((a: any) => a.code === selectedCodes[2]);
               if (area) {
                  form.value.area = area.name;
                  form.value.areaCode = area.code;
                  console.log('选中区域:', area.name);
               }
            }
         }
      }

      console.log('最终地区信息:', {
         province: form.value.province,
         city: form.value.city,
         area: form.value.area,
         codes: {
            provinceCode: form.value.provinceCode,
            cityCode: form.value.cityCode,
            areaCode: form.value.areaCode
         }
      });

   } catch (error) {
      console.error('地区选择处理失败:', error);
   }
};

// 根据省市区名称反向查找对应的code值
const findRegionCodes = (provinceName: string, cityName: string, areaName: string) => {
   console.log('查找地区编码:', { provinceName, cityName, areaName });

   try {
      const codes: string[] = [];

      // 查找省份
      const province = regionOptions.value.find(p => p.name === provinceName);
      if (province) {
         codes.push(province.code);
         console.log('找到省份编码:', province.code);

         // 查找城市 (现在在children字段中)
         if (cityName && province.children) {
            const city = province.children.find((c: any) => c.name === cityName);
            if (city) {
               codes.push(city.code);
               console.log('找到城市编码:', city.code);

               // 查找区域
               if (areaName && city.children) {
                  const area = city.children.find((a: any) => a.name === areaName);
                  if (area) {
                     codes.push(area.code);
                     console.log('找到区域编码:', area.code);
                  }
               }
            }
         }
      }

      console.log('最终找到的编码:', codes);
      return codes;
   } catch (error) {
      console.error('查找地区编码失败:', error);
      return [];
   }
};


// 处理编辑数据的地区信息
const handleEditRegionData = (item: any) => {
   if (item.province && item.city && item.area) {
      // 使用 nextTick 确保地区数据已加载
      setTimeout(() => {
         const codes = findRegionCodes(item.province, item.city, item.area);
         if (codes.length > 0) {
            form.value.regionValue = codes;
            form.value.provinceCode = codes[0] || '';
            form.value.cityCode = codes[1] || '';
            form.value.areaCode = codes[2] || '';
            console.log('编辑模式地区数据已设置:', {
               regionValue: form.value.regionValue,
               province: form.value.province,
               city: form.value.city,
               area: form.value.area
            });
         }
      }, 100); // 短暂延迟确保数据已加载
   }
};

// 处理编辑模式的spu_data数据回显
const handleEditProductData = (editData: any) => {
   console.log('=== 开始处理编辑模式数据 ===');
   console.log('完整编辑数据:', editData);
   console.log('editData.spu_data:', editData.spu_data);

   // 根据form.type判断如何处理product_data
   // type = 1: 纯出库单，product_data是出库产品
   // type = 2: 纯补库单，product_data是补库产品  
   // type = 0: 混合单，需要区分处理

   const formType = editData.type || form.value.type || 0;
   console.log('订单类型:', formType);

   let allOutboundProducts: any[] = []; // 出库产品
   const restockCategories: any[] = []; // 补库类别

   // 处理spu_data数组
   if (editData.spu_data && Array.isArray(editData.spu_data)) {
      console.log('找到spu_data数组，长度:', editData.spu_data.length);

      editData.spu_data.forEach((spuItem: any, spuIndex: number) => {
         console.log(`\n=== 处理第${spuIndex + 1}个SPU项 ===`);
         console.log('SPU数据:', spuItem);

         // 创建补库类别（每个SPU都是一个类别）
         const restockCategory = {
            id: spuItem.id,
            category: spuItem.name || `类别${spuIndex + 1}`,
            spu_id: spuItem.id,
            spu_name: spuItem.name,
            name: spuItem.name,
            unit_id: spuItem.unit_id,
            unit_name: spuItem.unit_name,
            type: 'category',
            // **核心修正**: 直接使用SPU顶层数据作为初始待出库显示
            pending_outbound_display: (spuItem.num || '0') + (spuItem.unit_name || ''),
            children: [] as any[] // 修复类型错误：明确指定为any数组
         };

         console.log(`创建补库类别，初始待出库显示为:`, restockCategory.pending_outbound_display);
         restockCategories.push(restockCategory);

         // 处理该SPU下的product_data
         if (spuItem.product_data && Array.isArray(spuItem.product_data)) {
            console.log(`SPU "${spuItem.name}" 包含 ${spuItem.product_data.length} 个产品`);

            spuItem.product_data.forEach((product: any, productIndex: number) => {
               console.log(`处理产品 ${productIndex + 1}:`, product);

               if (formType === 1 || (formType === 0 && product.is_outbound)) {
                  // 这是出库产品
                  const outboundProduct = {
                     id: product.id,
                     name: product.name,
                     no: product.no || '',
                     specification: product.specification || '',
                     // 更新字段映射：measure_unit -> measure_unit_name
                     measure_unit_name: product.measure_unit_name || product.measure_unit || '',
                     open_unit_num: product.open_unit_num || 0,
                     open_unit_name: product.open_unit_name || product.open_unit || '',
                     // 更新字段映射：spu_measure_unit -> spu_measure_unit_name
                     spu_measure_unit_name: product.spu_measure_unit_name || product.spu_measure_unit || '',
                     // 回显出库数量（使用原始的num字段）   
                     num: parseFloat(product.num) || parseFloat(product.open_unit_num) || 1,
                     unit_price: parseFloat(product.unit_price) || 0,
                     discount: parseFloat(product.discount) || 0,
                     stock: parseFloat(product.stock) || 0,
                     // 更新字段映射：supplier (字符串) -> suppliers (数组)
                     supplier: Array.isArray(product.suppliers) && product.suppliers.length > 0
                        ? product.suppliers[0].name
                        : (product.supplier || ''),
                     suppliers: Array.isArray(product.suppliers)
                        ? product.suppliers
                        : (product.supplier ? [{ name: product.supplier }] : []),
                     discountPrice: 0,
                     totalAmount: 0,
                     // 新增：回显出库量字段（spu_unit_num + spu_unit_name）
                     spu_unit_num: parseFloat(product.spu_unit_num) || 0,
                     spu_unit_name: product.spu_unit_name || '',
                     // 拼接显示的出库量
                     outbound_display: (parseFloat(product.spu_unit_num) || 0) + (product.spu_unit_name || ''),
                     // 新增：单位转换所需的ID信息和关键的unit_num字段
                     spu_measure_unit_id: product.spu_measure_unit_id || product.measure_unit_id,
                     spu_unit_id: product.spu_unit_id || product.unit_id,
                     measure_unit_id: product.measure_unit_id,
                     unit_id: product.unit_id,
                     // 关键字段：用于单位转换计算的 unit_num
                     unit_num: parseFloat(product.unit_num) || 1,
                     // 初始化用于后续计算的字段
                     calculated_outbound_volume_num: parseFloat(product.spu_unit_num) || 0,
                  };

                  console.log('✅ 创建出库产品:', outboundProduct);
                  console.log('出库量回显:', {
                     spu_unit_num: outboundProduct.spu_unit_num,
                     spu_unit_name: outboundProduct.spu_unit_name,
                     outbound_display: outboundProduct.outbound_display
                  });
                  calculateRowAmount(outboundProduct);
                  allOutboundProducts.push(outboundProduct);

               } else {
                  // 这是补库产品，添加到对应SPU类别的children中
                  const restockProduct = {
                     id: product.id,
                     name: product.name,
                     no: product.no || '',
                     spu: product.no || product.id,
                     specification: product.specification || '',
                     rules: product.specification || '',
                     // 更新字段映射：measure_unit -> measure_unit_name
                     unit: product.measure_unit_name || product.measure_unit || product.unit_name || '个',
                     stock: parseFloat(product.stock) || 0,
                     // 更新字段映射：supplier (字符串) -> suppliers (数组)
                     supplier: Array.isArray(product.suppliers) && product.suppliers.length > 0
                        ? product.suppliers[0].name
                        : (product.supplier || ''),
                     suppliers: Array.isArray(product.suppliers)
                        ? product.suppliers
                        : (product.supplier ? [{ name: product.supplier }] : []),
                     category: restockCategory.category,
                     spu_id: spuItem.id,
                     spu_name: spuItem.name,
                     // 回显出库数量（使用原始的num字段）
                     num: parseFloat(product.num) || parseFloat(product.open_unit_num) || 0,
                     discount: parseFloat(product.discount) || 0,
                     unit_price: parseFloat(product.unit_price) || 0,
                     discountPrice: 0,
                     totalAmount: 0,
                     type: 'product',
                     volume_per_unit: extractVolumeFromSpecification(product.specification || ''),
                     open_unit_num: product.open_unit_num || 0,
                     open_unit_name: product.open_unit_name || '',
                     // 新增：回显出库量字段（spu_unit_num + spu_unit_name）
                     spu_unit_num: parseFloat(product.spu_unit_num) || 0,
                     spu_unit_name: product.spu_unit_name || '',
                     // 拼接显示的出库量
                     outbound_display: (parseFloat(product.spu_unit_num) || 0) + (product.spu_unit_name || ''),
                     // 新增：单位转换所需的ID信息和关键的unit_num字段
                     spu_measure_unit_id: product.spu_measure_unit_id || product.measure_unit_id,
                     spu_unit_id: product.spu_unit_id || product.unit_id,
                     measure_unit_id: product.measure_unit_id,
                     unit_id: product.unit_id,
                     // 关键字段：用于单位转换计算的 unit_num
                     unit_num: parseFloat(product.unit_num) || 1,
                     // 初始化用于后续计算的字段
                     calculated_outbound_volume_num: parseFloat(product.spu_unit_num) || 0,
                  };

                  console.log('✅ 创建补库产品:', restockProduct);
                  console.log('补库产品出库量回显:', {
                     spu_unit_num: restockProduct.spu_unit_num,
                     spu_unit_name: restockProduct.spu_unit_name,
                     outbound_display: restockProduct.outbound_display
                  });
                  calculateRowAmount(restockProduct);

                  // 添加到当前SPU类别的children中
                  restockCategory.children.push(restockProduct);
                  console.log(`✅ 补库产品已添加到类别 "${restockCategory.category}"，当前children数量:`, restockCategory.children.length);
               }
            });
         } else {
            console.log(`⚠️  SPU "${spuItem.name}" 没有product_data或不是数组`);
         }
      });
   }

   // 如果没有明确的类型判断，默认都作为补库产品处理
   if (formType === 0 && allOutboundProducts.length === 0) {
      console.log('🔄 默认将所有产品作为补库产品处理');

      editData.spu_data?.forEach((spuItem: any, spuIndex: number) => {
         const targetCategory = restockCategories[spuIndex];

         if (spuItem.product_data && Array.isArray(spuItem.product_data)) {
            spuItem.product_data.forEach((product: any) => {
               const restockProduct = {
                  id: product.id,
                  name: product.name,
                  no: product.no || '',
                  spu: product.no || product.id,
                  specification: product.specification || '',
                  rules: product.specification || '',
                  // 更新字段映射：measure_unit -> measure_unit_name
                  unit: product.measure_unit_name || product.measure_unit || product.unit_name || '个',
                  stock: parseFloat(product.stock) || 0,
                  // 更新字段映射：supplier (字符串) -> suppliers (数组)
                  supplier: Array.isArray(product.suppliers) && product.suppliers.length > 0
                     ? product.suppliers[0].name
                     : (product.supplier || ''),
                  suppliers: Array.isArray(product.suppliers)
                     ? product.suppliers
                     : (product.supplier ? [{ name: product.supplier }] : []),
                  category: targetCategory.category,
                  spu_id: spuItem.id,
                  spu_name: spuItem.name,
                  // 回显出库数量（使用原始的num字段）
                  num: parseFloat(product.num) || parseFloat(product.open_unit_num) || 0,
                  discount: parseFloat(product.discount) || 0,
                  unit_price: parseFloat(product.unit_price) || 0,
                  discountPrice: 0,
                  totalAmount: 0,
                  type: 'product',
                  volume_per_unit: extractVolumeFromSpecification(product.specification || ''),
                  open_unit_num: parseFloat(product.open_unit_num) || 0,
                  open_unit_name: product.open_unit_name || '',
                  // 新增：回显出库量字段（spu_unit_num + spu_unit_name）
                  spu_unit_num: parseFloat(product.spu_unit_num) || 0,
                  spu_unit_name: product.spu_unit_name || '',
                  // 拼接显示的出库量
                  outbound_display: (parseFloat(product.spu_unit_num) || 0) + (product.spu_unit_name || ''),
                  // 新增：单位转换所需的ID信息
                  spu_measure_unit_id: product.spu_measure_unit_id || product.measure_unit_id,
                  spu_unit_id: product.spu_unit_id || product.unit_id,
                  measure_unit_id: product.measure_unit_id,
                  unit_id: product.unit_id,
                  // 关键字段：用于单位转换计算的 unit_num
                  unit_num: parseFloat(product.unit_num) || 1,
                  // 初始化用于后续计算的字段
                  calculated_outbound_volume_num: 0,
               };

               console.log('✅ 默认补库产品出库量回显:', {
                  spu_unit_num: restockProduct.spu_unit_num,
                  spu_unit_name: restockProduct.spu_unit_name,
                  outbound_display: restockProduct.outbound_display
               });

               calculateRowAmount(restockProduct);
               targetCategory.children.push(restockProduct);

               console.log(`✅ 默认补库产品已添加到类别 "${targetCategory.category}"`);
            });
         }
      });
   }

   // 设置表单数据
   form.value.product_data = allOutboundProducts;
   restockProductsData.value = restockCategories;

   console.log('=== 最终数据设置 ===');
   console.log('出库产品数量:', allOutboundProducts.length);
   console.log('补库类别数量:', restockCategories.length);

   // 检查每个类别的children和出库量回显
   restockCategories.forEach((category, index) => {
      console.log(`📊 类别 ${index + 1} "${category.category}": ${category.children?.length || 0} 个子产品`);
      if (category.children && category.children.length > 0) {
         category.children.forEach((child: any, childIndex: number) => {
            console.log(`   ${childIndex + 1}. ${child.name} (ID: ${child.id}, 数量: ${child.num}, 出库量: ${child.outbound_display})`);
         });
         // 初始化SPU类别的待出库显示（基于回显数据计算）
         updateSPUPendingOutbound(category.children[0]);
      }
   });

   // 检查出库产品的出库量回显
   allOutboundProducts.forEach((product, index) => {
      console.log(`📊 出库产品 ${index + 1} "${product.name}": 出库量: ${product.outbound_display}`);
   });

   // 更新展开行数组和其他计算
   updateExpandedRows();

   restockCategories.forEach(category => {
      updateCategoryPendingOutbound(category.id);
   });

   // 统计总数
   const totalRestockProducts = restockCategories.reduce((sum, category) => {
      return sum + (category.children ? category.children.length : 0);
   }, 0);

   console.log('=== 处理完成 ===');
   console.log('最终restockProductsData.value:', restockProductsData.value);
   console.log('expandedRows.value:', expandedRows.value);

   if (allOutboundProducts.length > 0) {
      ElMessage.success(`已回显 ${allOutboundProducts.length} 个出库产品`);
   }

   if (totalRestockProducts > 0) {
      ElMessage.success(`已回显 ${totalRestockProducts} 个补库产品到 ${restockCategories.length} 个类别`);
   }

   // 强制触发视图更新
   setTimeout(() => {
      console.log('🔄 强制更新后的数据检查:');
      console.log('restockProductsData.value:', restockProductsData.value);
      restockProductsData.value.forEach((cat, idx) => {
         console.log(`类别${idx + 1} "${cat.category}" children:`, cat.children?.length || 0);
      });
   }, 50);
};

// 打开弹窗
const openLoading = (item?: any) => {

   if (item) {
      // 编辑模式：填充现有数据
      console.log('编辑模式，填充数据:', item);
      form.value = {
         id: item.id || "", // 订单ID
         customer_id: item.customer_id || "", // 客户ID
         customer_name: item.customer_name || "", // 客户名称
         customer_phone: item.customer_phone || "", // 客户电话
         province: item.province || "", // 省
         city: item.city || "", // 市
         area: item.area || "", // 区
         provinceCode: item.provinceCode || "", // 省编码
         cityCode: item.cityCode || "", // 市编码
         areaCode: item.areaCode || "", // 区编码
         regionValue: [], // 稍后根据省市区信息设置
         address: item.address || "", // 地址
         org_member_id: item.org_member_id || "", // 组织成员ID
         org_member_name: item.org_member_name || item.contact_name || "", // 组织成员名称
         org_member_phone: item.org_member_phone || item.contact_phone || "", // 组织成员电话
         order_date: item.order_date || "", // 订单日期
         delivery_date: item.delivery_date || "", // 交货日期
         note: item.note || "", // 备注
         product_data: [], // 先初始化为空，稍后通过handleEditProductData处理
         orderDiscount: item.orderDiscount || 0, // 订单折扣
         finalAmount: item.finalAmount || item.total_amount || 0, // 最终金额
         status: item.status || 0, // 状态
         type: item.type || 0, // 类型
         warehouse_id: item.warehouse_id || "", // 获取仓库ID
      };

      console.log('仓库ID已设置:', form.value.warehouse_id);

      // 延迟处理地区数据
      handleEditRegionData(item);

      // 处理产品数据回显（包括出库产品和补库产品类别）
      handleEditProductData(item);

      // 延迟更新展开行，确保数据已加载
      setTimeout(() => {
         updateExpandedRows();
      }, 100);

      console.log('编辑数据已填充:', form.value);
   } else {
      // 新增模式：重置表单
      form.value = {
         customer_id: "",
         customer_name: "",
         customer_phone: "",
         province: "",
         city: "",
         area: "",
         provinceCode: "",
         cityCode: "",
         areaCode: "",
         regionValue: [],
         address: "",
         org_member_id: "",
         org_member_name: "",
         org_member_phone: "",
         order_date: "",
         delivery_date: "",
         note: "",
         product_data: [],
         orderDiscount: 0,
         finalAmount: 0,
         warehouse_id: "", // 新增模式时仓库ID为空
      };

      // 新增模式时清空补库产品数据
      restockProductsData.value = [];
      expandedRows.value = [];
   }

   dialogVisible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
   dialogVisible.value = false;
};

// 选择客户
const openSelectCustomersPopup = (e: any) => {
   console.log('打开选择客户弹窗');
   selectCustomersRef.value.openLoading();
   e.target.blur();
};

// 选择出库负责人
const openOutboundOrderManagerPopup = (e: any) => {
   console.log('打开选择出库负责人弹窗');
   outboundOrderManagerRef.value.openLoading();
   e.target.blur();
};

// 更新产品选择处理逻辑
const handleSelectProduct = (products: any[]) => {
   console.log('选择产品:', products, '当前产品类型:', currentProductType.value);

   if (currentProductType.value === 'outbound') {
      // 出库产品处理
      console.log('处理出库产品数据');
      const processedProducts = products.map(product => ({
         ...product,
         // 保持原有字段用于显示
         id: product.id,
         name: product.name,
         no: product.no,
         specification: product.specification,
         // 更新字段映射：确保使用新的字段名
         measure_unit_name: product.measure_unit_name || product.measure_unit || '',
         open_unit_name: product.open_unit_name || product.open_unit || '',
         spu_measure_unit_name: product.spu_measure_unit_name || product.spu_measure_unit || '',
         count: product.count,
         // 更新供应商字段映射：supplier (字符串) -> suppliers (数组)
         suppliers: Array.isArray(product.suppliers)
            ? product.suppliers
            : (product.supplier ? [{ name: product.supplier }] : []),
         // 用户需要填写的字段
         num: product.num || 0, // 出库数量（用户填写）
         unit_price: product.unit_price || product.price || 0, // 出库单价
         discount: product.discount || 0, // 折扣
         // 计算字段
         discountPrice: 0,
         totalAmount: 0,
         stock: product.stock || 0, // 库存
         // 新增：单位转换所需的ID信息和关键的unit_num字段
         spu_measure_unit_id: product.spu_measure_unit_id || product.measure_unit_id,
         spu_unit_id: product.spu_unit_id || product.unit_id,
         measure_unit_id: product.measure_unit_id,
         unit_id: product.unit_id,
         // 关键字段：用于单位转换计算的 unit_num
         unit_num: parseFloat(product.unit_num) || 1,
      }));

      // 检查是否有重复产品
      const existingIds = form.value.product_data.map((item: any) => item.id);
      const newProducts = processedProducts.filter(product => !existingIds.includes(product.id));

      if (newProducts.length === 0) {
         ElMessage.warning('所选产品已存在，未添加新产品');
         return;
      }

      // 合并到现有产品数据中
      form.value.product_data.push(...newProducts);

      // 重新计算每行金额
      newProducts.forEach(product => {
         calculateRowAmount(product);
      });

      console.log('出库产品数据已更新:', form.value.product_data);
      ElMessage.success(`已添加 ${newProducts.length} 个出库产品`);

   } else if (currentProductType.value === 'restock' && currentRestockCategory.value) {
      // 补库产品处理
      console.log('处理补库产品数据，目标类别:', currentRestockCategory.value);
      const categoryIndex = restockProductsData.value.findIndex(cat => cat.id === currentRestockCategory.value.id);

      if (categoryIndex > -1) {
         const processedProducts = products.map(product => ({
            // 基础产品信息
            id: product.id, // 使用真实的产品ID
            name: product.name,
            no: product.no,
            spu: product.no || product.id,
            specification: product.specification || '',
            rules: product.specification || '',
            // 补库产品特有字段 - 更新字段映射
            unit: product.measure_unit_name || product.measure_unit || product.unit_name || '个',
            stock: product.stock || 0, // 使用真实库存数据
            // 更新供应商字段映射：supplier (字符串) -> suppliers (数组)
            supplier: Array.isArray(product.suppliers) && product.suppliers.length > 0
               ? product.suppliers[0].name
               : (product.supplier || ''),
            suppliers: Array.isArray(product.suppliers)
               ? product.suppliers
               : (product.supplier ? [{ name: product.supplier }] : []),
            category: currentRestockCategory.value.category,
            spu_id: currentRestockCategory.value.spu_id,
            spu_name: currentRestockCategory.value.spu_name,
            // 用户填写字段
            num: 0, // 默认出库数量为0
            discount: 0, // 拆零数量
            unit_price: product.price || product.unit_price || 0, // 单价
            // 计算字段
            discountPrice: 0,
            totalAmount: 0,
            type: 'product',
            volume_per_unit: extractVolumeFromSpecification(product.specification || ''),
            // 新增：单位转换所需的ID信息和关键的unit_num字段
            spu_measure_unit_id: product.spu_measure_unit_id || product.measure_unit_id,
            spu_unit_id: product.spu_unit_id || product.unit_id,
            measure_unit_id: product.measure_unit_id,
            unit_id: product.unit_id,
            // 关键字段：用于单位转换计算的 unit_num
            unit_num: parseFloat(product.unit_num) || 1,
            // **核心修正：初始化用于累加的数值字段**
            calculated_outbound_volume_num: 0,
         }));

         // 检查是否有重复产品
         const existingProductIds = restockProductsData.value[categoryIndex].children.map((child: any) => child.id);
         const newProducts = processedProducts.filter(product => !existingProductIds.includes(product.id));

         if (newProducts.length === 0) {
            ElMessage.warning('所选产品已存在于该类别中');
            return;
         }

         // 添加到对应类别的children中
         restockProductsData.value[categoryIndex].children.push(...newProducts);

         // 重新计算新添加产品的金额
         newProducts.forEach(product => {
            calculateRowAmount(product);
         });

         // 更新类别的待出库数量
         updateCategoryPendingOutbound(currentRestockCategory.value.id);

         console.log(`补库产品已添加到${currentRestockCategory.value.category}:`, newProducts);
         ElMessage.success(`已向${currentRestockCategory.value.category}添加 ${newProducts.length} 个产品`);
      }
   }

   // 重新计算总金额
   calculateOrderTotal();

   // 重置选择状态
   currentProductType.value = '';
   currentRestockCategory.value = null;
};

// 补库产品数据（树形结构）- 从spu_data动态生成
const restockProductsData = ref<any[]>([]);

// 移除重复的 expandedRows 声明
// const expandedRows = ref<number[]>([]);

// 更新展开行数组
const updateExpandedRows = () => {
   // 自动展开所有类别
   expandedRows.value = restockProductsData.value.map(category => category.id);
   console.log('更新展开行:', expandedRows.value);
};

// 当前选择的产品类型和类别
const currentProductType = ref(''); // 'outbound' 或 'restock'
const currentRestockCategory = ref<any>(null);

// 提取规格型号中的数字（升数）
const extractVolumeFromSpecification = (specification: string): number => {
   if (!specification) return 0;
   const match = specification.match(/(\d+(?:\.\d+)?)L/i);
   return match ? parseFloat(match[1]) : 0;
};

// 判断是否为开发环境
const isDevelopment = computed(() => {
   // 修复TypeScript错误：使用更兼容的方式判断开发环境
   return (typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'));
});

// 单位转换缓存，避免重复请求
const conversionCache = ref<Map<string, any>>(new Map());

// 单位转换函数
const convertUnit = async (num: number, fromUnitId: number, toUnitId: number): Promise<any> => {
   try {
      // 如果单位相同，直接返回原数量
      if (fromUnitId === toUnitId) {
         return {
            success: true,
            convertedNum: num,
            unit_name: ''
         };
      }

      // 生成缓存key
      const cacheKey = `${num}_${fromUnitId}_${toUnitId}`;

      // 检查缓存
      if (conversionCache.value.has(cacheKey)) {
         console.log('使用缓存的转换结果:', cacheKey);
         return conversionCache.value.get(cacheKey);
      }

      console.log('调用单位转换接口:', {
         num: num,
         unit_id: fromUnitId,
         to_unit_id: toUnitId
      });

      const response = await api.publicFun.getUnitConversion({
         num: num,
         unit_id: fromUnitId,
         to_unit_id: toUnitId
      });

      if (response.code === 200 && response.data && typeof response.data.result !== 'undefined') {
         const result = {
            success: true,
            // 核心修正：从 response.data.result 获取转换后的数字
            convertedNum: response.data.result,
            // 接口不返回单位，所以这里为空
            unit_name: '',
            originalNum: num,
            fromUnitId: fromUnitId,
            toUnitId: toUnitId
         };

         // 缓存结果
         conversionCache.value.set(cacheKey, result);

         console.log('单位转换成功:', result);
         return result;
      } else {
         console.error('单位转换失败:', response.message || '返回数据结构不正确');
         return {
            success: false,
            convertedNum: num,
            unit_name: '',
            error: response.message || '返回数据结构不正确'
         };
      }
   } catch (error) {
      console.error('单位转换异常:', error);
      return {
         success: false,
         convertedNum: num,
         unit_name: '',
         error: '转换异常'
      };
   }
};

// 异步计算产品出库量（支持单位转换）
const calculateOutboundVolumeAsync = async (product: any): Promise<string> => {
   const userInputNum = parseFloat(product.num) || 0;

   if (userInputNum === 0) {
      return '0';
   }

   // 如果有单位ID信息，调用后端转换接口
   if (product.spu_measure_unit_id && product.spu_unit_id && product.unit_num) {
      try {
         // 关键修正：计算实际转换数量 = 用户输入数量 × unit_num
         const actualConversionNum = userInputNum * parseFloat(product.unit_num);

         console.log(`产品 ${product.name} 转换计算:`, {
            用户输入数量: userInputNum,
            unit_num: product.unit_num,
            实际转换数量: actualConversionNum,
            源单位ID: product.spu_measure_unit_id,
            目标单位ID: product.spu_unit_id
         });

         const conversionResult = await convertUnit(
            actualConversionNum,           // 传递 num × unit_num
            product.spu_measure_unit_id,   // 源单位ID (采购单位)
            product.spu_unit_id            // 目标单位ID (规格单位)
         );

         if (conversionResult.success) {
            const displayResult = `${conversionResult.convertedNum}${conversionResult.unit_name}`;
            console.log(`产品 ${product.name} 转换成功:`, displayResult);
            return displayResult;
         } else {
            console.warn('单位转换失败，使用默认计算:', conversionResult.error);
         }
      } catch (error) {
         console.error('异步计算出库量失败:', error);
      }
   }

   // 降级到原有的计算方式
   const volumePerUnit = product.volume_per_unit || extractVolumeFromSpecification(product.specification || '');
   const totalVolume = userInputNum * volumePerUnit;
   return totalVolume > 0 ? `${totalVolume}L` : '0L';
};

// // 计算产品出库量（出库数量 × 规格型号）- 同步版本，用于模板显示
const calculateOutboundVolume = (product: any): string => {
   // 编辑模式下，如果有回显的出库量数据，优先显示
   if (form.value.id && product.outbound_display) {
      return product.outbound_display;
   }

   // 新增模式下或没有回显数据时的计算逻辑
   const quantity = parseFloat(product.num) || 0;
   const volumePerUnit = product.volume_per_unit || extractVolumeFromSpecification(product.specification || '');
   const totalVolume = quantity * volumePerUnit;
   return totalVolume > 0 ? `${totalVolume}L` : '0L';
};

// 异步更新产品的出库量显示
const updateProductOutboundDisplay = async (product: any) => {
   if (!product.spu_measure_unit_id || !product.spu_unit_id) {
      console.log('产品缺少单位ID信息，跳过异步转换:', product.name);
      return;
   }

   try {
      const outboundDisplay = await calculateOutboundVolumeAsync(product);

      // 更新产品的显示字段（但不覆盖编辑模式的回显数据）
      if (!form.value.id || !product.outbound_display) {
         product.calculated_outbound_display = outboundDisplay;
         console.log(`产品 ${product.name} 异步出库量计算完成:`, outboundDisplay);
      }
   } catch (error) {
      console.error(`产品 ${product.name} 异步出库量计算失败:`, error);
   }
};

// 计算产品的待出库量（显示出库后的变化）
const calculateProductPendingOutbound = (product: any): string => {
   const outboundQuantity = parseFloat(product.num) || 0;
   const volumePerUnit = product.volume_per_unit || extractVolumeFromSpecification(product.specification || '');
   const outboundVolume = outboundQuantity * volumePerUnit;
   return outboundVolume > 0 ? `${outboundVolume}L` : '0L';
};

// 更新类别的待出库数量
const updateCategoryPendingOutbound = (categoryId: number) => {
   const category = restockProductsData.value.find(cat => cat.id === categoryId);
   if (category && category.children) {
      // 计算该类别下所有产品的出库总量
      const totalOutboundVolume = category.children.reduce((sum: number, product: any) => {
         const quantity = parseFloat(product.num) || 0;
         const volumePerUnit = product.volume_per_unit || extractVolumeFromSpecification(product.specification || '');
         return sum + (quantity * volumePerUnit);
      }, 0);

      // 从原始待出库量中减去已出库量
      const originalPendingOutbound = category.original_pending_outbound || 0;
      category.pending_outbound = Math.max(0, originalPendingOutbound - totalOutboundVolume);

      console.log(`类别 ${category.category} 待出库更新:`, {
         原始待出库: originalPendingOutbound,
         总出库量: totalOutboundVolume,
         剩余待出库: category.pending_outbound
      });
   }
};

// 获取类别库存颜色
const getCategoryStockColor = (pendingOutbound: number): string => {
   if (pendingOutbound <= 0) {
      return '#ef4444'; // 红色 - 库存不足
   } else if (pendingOutbound <= 100) {
      return '#f59e0b'; // 黄色 - 库存偏低
   } else {
      return '#10b981'; // 绿色 - 库存正常
   }
};

// 计算单行金额
const calculateRowAmount = (row: any) => {
   const quantity = parseFloat(row.num) || 0;
   const unitPrice = parseFloat(row.unit_price) || 0;
   const discount = parseFloat(row.discount) || 0;

   // 计算折后价
   const discountPrice = unitPrice * (1 - discount / 100);
   row.discountPrice = discountPrice.toFixed(2);

   // 计算总金额
   const totalAmount = quantity * discountPrice;
   row.totalAmount = totalAmount.toFixed(2);

   console.log('计算行金额:', {
      product: row.name,
      quantity,
      unitPrice,
      discount,
      discountPrice: row.discountPrice,
      totalAmount: row.totalAmount
   });

   // 重新计算整单金额
   calculateOrderTotal();
};

// 计算整单总金额
const calculateOrderTotal = () => {
   // 计算出库产品总金额
   const outboundTotal = form.value.product_data.reduce((sum: number, product: any) => {
      return sum + (parseFloat(product.totalAmount) || 0);
   }, 0);

   // 计算补库产品总金额
   const restockTotal = restockProductsData.value.reduce((sum: number, category: any) => {
      if (category.children && category.children.length > 0) {
         const categoryTotal = category.children.reduce((categorySum: number, product: any) => {
            return categorySum + (parseFloat(product.totalAmount) || 0);
         }, 0);
         return sum + categoryTotal;
      }
      return sum;
   }, 0);

   const subtotal = outboundTotal + restockTotal;
   const orderDiscount = parseFloat(form.value.orderDiscount) || 0;
   const finalAmount = subtotal * (1 - orderDiscount / 100);

   form.value.finalAmount = finalAmount.toFixed(2);

   console.log('整单金额计算:', {
      outboundTotal: outboundTotal.toFixed(2),
      restockTotal: restockTotal.toFixed(2),
      subtotal: subtotal.toFixed(2),
      orderDiscount,
      finalAmount: form.value.finalAmount
   });
};

// 打开出库产品选择弹窗
const openSelectProductsPopup = () => {
   if(!form.value.customer_id){
      ElMessage.error('请先选择客户');
      return;
   }
   console.log('=== 打开出库产品选择弹窗 DEBUG ===');
   currentProductType.value = 'outbound';

   
   // 详细检查产品数据
   console.log('当前出库产品数据 form.value.product_data:');
   console.log('数组长度:', form.value.product_data.length);
   form.value.product_data.forEach((item, index) => {
      console.log(`  第${index + 1}个产品:`, {
         id: item.id,
         name: item.name,
         id_type: typeof item.id
      });
   });
   
   // 收集已存在的出库产品ID
   const existingIds = form.value.product_data.map((item: any) => item.id);
   console.log('提取的出库产品ID原始数组:', existingIds);
   console.log('ID数组是否为数组:', Array.isArray(existingIds));
   console.log('ID数组长度:', existingIds.length);
   console.log('ID数组内容详情:');
   existingIds.forEach((id, index) => {
      console.log(`  [${index}]: ${id} (类型: ${typeof id})`);
   });
   
   // 出库产品不需要SPU限制，传递null作为SPU ID，传递仓库ID和已存在的产品ID
   console.log('即将调用 selectProductsRef.value.openLoading，参数:');
   console.log('  spuId: null');
   console.log('  warehouseId:', form.value.warehouse_id);
   console.log('  existingIds:', existingIds);
   // 将客户id和仓库id传递给selectProductsRef.value.openLoading
   selectProductsRef.value.openLoading(null, form.value.warehouse_id, existingIds, form.value.customer_id);
};

// 打开补库产品选择弹窗
const openSelectRestockProductsPopup = (category: any) => {
   console.log('=== 打开补库产品选择弹窗 DEBUG ===');
   console.log('类别信息:', category.category, 'SPU ID:', category.id, '仓库ID:', form.value.warehouse_id);
   currentProductType.value = 'restock';
   currentRestockCategory.value = category;
   
   // 详细检查类别下的产品数据
   console.log('当前类别子产品 category.children:');
   if (category.children && Array.isArray(category.children)) {
      console.log('子产品数组长度:', category.children.length);
      category.children.forEach((item, index) => {
         console.log(`  第${index + 1}个子产品:`, {
            id: item.id,
            name: item.name,
            id_type: typeof item.id
         });
      });
   } else {
      console.log('没有子产品或children不是数组');
   }
   
   // 收集该类别下已存在的产品ID
   const existingIds = category.children?.map((p: any) => p.id) || [];
   console.log('提取的补库产品ID原始数组:', existingIds);
   console.log('ID数组是否为数组:', Array.isArray(existingIds));
   console.log('ID数组长度:', existingIds.length);
   console.log('ID数组内容详情:');
   existingIds.forEach((id, index) => {
      console.log(`  [${index}]: ${id} (类型: ${typeof id})`);
   });
   
   // 传递SPU ID、仓库ID和已存在的产品ID给产品弹窗
   console.log('即将调用 selectProductsRef.value.openLoading，参数:');
   console.log('  spuId:', category.id);
   console.log('  warehouseId:', form.value.warehouse_id);
   console.log('  existingIds:', existingIds);
   
   selectProductsRef.value.openLoading(category.id, form.value.warehouse_id, existingIds);
};

// 移除出库产品
const handleRemoveProduct = (row: any) => {
   const index = form.value.product_data.findIndex((item: any) => item.id === row.id);
   if (index > -1) {
      form.value.product_data.splice(index, 1);
      calculateOrderTotal();
      console.log('移除出库产品:', row.name);
      ElMessage.success(`已移除产品：${row.name}`);
   }
};

// 移除补库产品
const handleRemoveRestockProduct = (product: any, category: any) => {
   const categoryIndex = restockProductsData.value.findIndex(cat => cat.id === category.id);
   if (categoryIndex > -1) {
      const productIndex = restockProductsData.value[categoryIndex].children.findIndex((item: any) => item.id === product.id);
      if (productIndex > -1) {
         restockProductsData.value[categoryIndex].children.splice(productIndex, 1);

         // 重新计算总金额
         calculateOrderTotal();

         // 更新类别的待出库数量
         updateCategoryPendingOutbound(category.id);

         console.log('移除补库产品:', product.name, '从类别:', category.category);
         ElMessage.success(`已移除补库产品：${product.name}`);
      }
   }
};

// 处理选择客户
const handleSelectCustomer = (customer: any) => {
   console.log('选择客户:', customer);

   form.value.customer_id = customer.id;
   form.value.customer_name = customer.name;
   form.value.customer_phone = customer.phone;
   form.value.address = customer.address;

   // 解析客户的地区信息
   if (customer.region) {
      const regionParts = customer.region.trim().split(/\s+/);
      if (regionParts.length >= 3) {
         const provinceName = regionParts[0];
         const cityName = regionParts[1];
         const areaName = regionParts[2];

         // 设置地区名称
         form.value.province = provinceName;
         form.value.city = cityName;
         form.value.area = areaName;

         // 查找对应的地区编码并设置级联选择器的值
         const codes = findRegionCodes(provinceName, cityName, areaName);
         if (codes.length > 0) {
            form.value.regionValue = codes;
            form.value.provinceCode = codes[0] || '';
            form.value.cityCode = codes[1] || '';
            form.value.areaCode = codes[2] || '';
         }
      }
   }

   console.log('客户信息已填充:', {
      customer_name: form.value.customer_name,
      customer_phone: form.value.customer_phone,
      province: form.value.province,
      city: form.value.city,
      area: form.value.area,
      address: form.value.address,
      regionValue: form.value.regionValue
   });

   ElMessage.success(`已选择客户：${customer.name}`);
};

// 出库负责人所需数据类型
interface OutboundOrderManager {
   id: number;
   Sname: string;
   name: string;
   Sphone: string;
   Sposition: string;
   num?: string;
}

// 处理选择出库负责人
const handleSelectOutboundOrderManager = (outboundOrderManager: OutboundOrderManager) => {
   console.log('选择出库负责人:', outboundOrderManager);

   form.value.org_member_id = outboundOrderManager.id;
   form.value.org_member_name = outboundOrderManager.name || outboundOrderManager.Sname;
   form.value.org_member_phone = outboundOrderManager.Sphone;

   console.log('负责人信息已填充:', {
      org_member_id: form.value.org_member_id,
      org_member_name: form.value.org_member_name,
      org_member_phone: form.value.org_member_phone
   });

   ElMessage.success(`已选择负责人：${form.value.org_member_name}`);
};

// 禁用交货日期早于出库日期的选项
const disabledDate = (time: Date) => {
   if (!form.value.order_date) {
      return false;
   }

   // 将出库日期字符串转换为Date对象
   const orderDate = new Date(form.value.order_date);
   // 交货日期不能早于出库日期
   return time.getTime() < orderDate.getTime();
};

// 处理出库数量变化 - 添加缺失的函数
const handleOutboundQuantityChange = (product: any) => {
   // 直接调用新的实时转换和更新函数
   handleOutboundNumChange(product);
};

// 提交表单
const handleSubmit = async () => {
   // 验证必填项
   if (!form.value.customer_name) {
      ElMessage.error('请选择客户');
      return;
   }

   if (!form.value.org_member_name) {
      ElMessage.error('请选择出库负责人');
      return;
   }

   if (!form.value.province || !form.value.city || !form.value.area) {
      ElMessage.error('请选择完整的收货地址（省市区）');
      return;
   }

   if (!form.value.order_date) {
      ElMessage.error('请选择出库日期');
      return;
   }

   if (!form.value.delivery_date) {
      ElMessage.error('请选择交货日期');
      return;
   }

   // 验证交货日期不能早于出库日期
   if (new Date(form.value.delivery_date) < new Date(form.value.order_date)) {
      ElMessage.error('交货日期不能早于出库日期');
      return;
   }

   // 出库数量不得小于1
   if (form.value.product_data.some((product: any) => parseInt(product.num) < 1)) {
      ElMessage.error('出库数量不得小于1');
      return;
   }

   try {
      // 准备出库产品数据
      const outboundProductData = form.value.product_data.map((product: any) => ({
         id: product.id, // 产品ID
         num: parseInt(product.num) || 1, // 出库数量
         unit_price: parseFloat(product.unit_price) || 0, // 出库单价
         discount: parseFloat(product.discount) || 0, // 折扣
         totalAmount: parseFloat(product.totalAmount) || 0 // 出库金额
      }));

      // 准备补库产品数据
      const restockProductData: any[] = [];
      restockProductsData.value.forEach(category => {
         if (category.children && category.children.length > 0) {
            category.children.forEach((product: any) => {
               if (product.type === 'product' && parseFloat(product.num) > 0) {
                  restockProductData.push({
                     id: product.id, // 产品ID
                     num: parseInt(product.num) || 0, // 出库数量
                     unit_price: parseFloat(product.unit_price) || 0, // 单价
                     discount: parseFloat(product.discount) || 0, // 折扣
                     totalAmount: parseFloat(product.totalAmount) || 0 // 出库金额
                  });
               }
            });
         }
      });

      // 合并出库产品和补库产品数据到同一个数组
      const allProductData = [...outboundProductData, ...restockProductData];

      // 准备提交数据
      const submitData = {
         id: form.value.id,
         customer_id: form.value.customer_id,
         customer_name: form.value.customer_name,
         customer_phone: form.value.customer_phone,
         province: form.value.province,
         city: form.value.city,
         area: form.value.area,
         address: form.value.address,
         org_member_id: form.value.org_member_id,
         org_member_name: form.value.org_member_name,
         org_member_phone: form.value.org_member_phone,
         order_date: form.value.order_date,
         delivery_date: form.value.delivery_date,
         note: form.value.note,
         // 所有产品数据（出库产品 + 补库产品）
         product_data: allProductData,
         // 整单金额信息
         orderDiscount: parseFloat(form.value.orderDiscount) || 0,
         finalAmount: parseFloat(form.value.finalAmount) || 0
      };

      console.log('提交表单数据:', submitData);
      console.log('出库产品数量:', outboundProductData.length);
      console.log('补库产品数量:', restockProductData.length);
      console.log('总产品数量:', allProductData.length);

      let response;

      if (form.value.id) {
         // 编辑模式：调用更新API
         response = await api.Outbound.editoutboundOrder(submitData, {
            id: form.value.id,
            customer_id: form.value.customer_id,
         });
         if (response.code === 200) {
            ElMessage.success('出库单更新成功！');
         } else {
            ElMessage.error(response.message || '更新出库单失败');
            return;
         }
      } else {
         // 新增模式：调用添加API
         response = await api.Outbound.addoutboundOrder(submitData);
         if (response.code === 200) {
            ElMessage.success('出库单创建成功！');
         } else {
            ElMessage.error(response.message || '创建出库单失败');
            return;
         }
      }

      closeDialog();
      // 通知父组件刷新列表
      emit('init');

   } catch (error) {
      console.error('提交出库单失败:', error);
      ElMessage.error(form.value.id ? '更新出库单失败，请重试' : '创建出库单失败，请重试');
   }
};

// 定义emits
const emit = defineEmits(['init']);

// 计算弹窗标题
const dialogTitle = computed(() => {
   return form.value.id ? '编辑出库单' : '新增出库单';
});

// 调试函数：查看出库量数据
const debugOutboundData = () => {
   console.log('=== 调试出库量数据 ===');

   // 出库产品数据
   console.log('📦 出库产品数据:');
   form.value.product_data.forEach((product: any, index: number) => {
      const userInputNum = parseFloat(product.num) || 0;
      const unitNum = parseFloat(product.unit_num) || 1;
      const actualConversionNum = userInputNum * unitNum;

      console.log(`${index + 1}. ${product.name}:`, {
         id: product.id,
         用户输入数量: userInputNum,
         unit_num: unitNum,
         实际转换数量: actualConversionNum,
         spu_unit_num: product.spu_unit_num,
         spu_unit_name: product.spu_unit_name,
         outbound_display: product.outbound_display,
         calculated_outbound_display: product.calculated_outbound_display,
         计算出库量: calculateOutboundVolume(product),
         单位ID信息: {
            spu_measure_unit_id: product.spu_measure_unit_id,
            spu_unit_id: product.spu_unit_id,
            measure_unit_id: product.measure_unit_id,
            unit_id: product.unit_id
         }
      });
   });

   // 补库产品数据
   console.log('📦 补库产品数据:');
   restockProductsData.value.forEach((category: any, catIndex: number) => {
      console.log(`类别 ${catIndex + 1}: ${category.category}`);
      if (category.children && category.children.length > 0) {
         category.children.forEach((product: any, prodIndex: number) => {
            const userInputNum = parseFloat(product.num) || 0;
            const unitNum = parseFloat(product.unit_num) || 1;
            const actualConversionNum = userInputNum * unitNum;

            console.log(`  ${prodIndex + 1}. ${product.name}:`, {
               id: product.id,
               用户输入数量: userInputNum,
               unit_num: unitNum,
               实际转换数量: actualConversionNum,
               spu_unit_num: product.spu_unit_num,
               spu_unit_name: product.spu_unit_name,
               outbound_display: product.outbound_display,
               calculated_outbound_display: product.calculated_outbound_display,
               计算出库量: calculateOutboundVolume(product),
               单位ID信息: {
                  spu_measure_unit_id: product.spu_measure_unit_id,
                  spu_unit_id: product.spu_unit_id,
                  measure_unit_id: product.measure_unit_id,
                  unit_id: product.unit_id
               }
            });
         });
      } else {
         console.log('  无子产品');
      }
   });

   // 单位转换缓存信息
   console.log('🔄 单位转换缓存:');
   conversionCache.value.forEach((result, key) => {
      console.log(`  ${key}:`, result);
   });

   console.log('=== 调试结束 ===');
};

defineExpose({
   openLoading,
});

// 处理出库数量变化时的实时单位转换
const handleOutboundNumChange = async (product: any) => {
   console.log('出库数量变化，开始实时转换:', product.name, '新数量:', product.num);
   
   const userInputNum = parseFloat(product.num) || 0;
   
   // 如果数量为0，清空转换结果
   if (userInputNum === 0) {
      product.calculated_outbound_display = '0';
      updateSPUPendingOutbound(product);
      calculateRowAmount(product); // 仍然需要计算金额
      return;
   }
   
   // 检查必要的转换参数
   if (!product.spu_measure_unit_id || !product.spu_unit_id || !product.unit_num) {
      console.warn('产品缺少单位转换必要参数:', {
         name: product.name,
         spu_measure_unit_id: product.spu_measure_unit_id,
         spu_unit_id: product.spu_unit_id,
         unit_num: product.unit_num
      });
      product.calculated_outbound_display = '计算错误';
      updateSPUPendingOutbound(product);
      calculateRowAmount(product);
      return;
   }
   
   try {
      // 计算实际转换数量：用户输入数量 × unit_num
      const actualConversionNum = userInputNum * parseFloat(product.unit_num);
      
      console.log('转换参数:', {
         产品名称: product.name,
         用户输入数量: userInputNum,
         unit_num: product.unit_num,
         实际转换数量: actualConversionNum,
         源单位ID: product.spu_measure_unit_id,
         目标单位ID: product.spu_unit_id
      });
      
      const conversionResult = await convertUnit(
         actualConversionNum,
         product.spu_measure_unit_id,
         product.spu_unit_id
      );
      
      if (conversionResult.success) {
         // 使用产品自身的spu_unit_name作为单位
         const targetUnitName = product.spu_unit_name || '';
         product.calculated_outbound_display = `${conversionResult.convertedNum}${targetUnitName}`;
         
         // **核心修正**: 更新用于累加的纯数字
         product.calculated_outbound_volume_num = conversionResult.convertedNum;

         console.log(`✅ 产品 ${product.name} 实时转换完成:`, {
            显示: product.calculated_outbound_display,
            数值: product.calculated_outbound_volume_num
         });

      } else {
         console.error(`❌ 产品 ${product.name} 转换失败:`, conversionResult.error);
         product.calculated_outbound_display = '转换失败';
         // **核心修正**: 转换失败时，将累加数字清零
         product.calculated_outbound_volume_num = 0;
      }
   } catch (error) {
      console.error(`❌ 产品 ${product.name} 转换异常:`, error);
      product.calculated_outbound_display = '转换异常';
      // **核心修正**: 转换异常时，将累加数字清零
      product.calculated_outbound_volume_num = 0;
   }
   
   // 更新SPU的待出库数量
   updateSPUPendingOutbound(product);
   
   // 重新计算行金额
   calculateRowAmount(product);
};


// 更新SPU类别的待出库数量（基于所有产品的出库量累积）
const updateSPUPendingOutbound = (changedProduct: any) => {
   // 找到该产品所属的SPU类别
   const category = restockProductsData.value.find(cat => cat.id === changedProduct.spu_id);
   
   if (!category || !category.children) {
      // 如果不是补库产品，则无需处理
      return;
   }

   console.log('更新SPU待出库数量，变化的产品:', changedProduct.name);
   
   // 计算该SPU下所有产品的出库量总和
   let totalOutboundVolume = 0;
   // 单位从第一个产品的SPU单位获取，确保一致性
   const totalOutboundUnit = category.children[0]?.spu_unit_name || '';
   
   category.children.forEach((product: any) => {
      // **核心修正**: 
      // 优先使用实时计算出的数字，如果没有，则使用编辑时回显的数字
      const volume = typeof product.calculated_outbound_volume_num === 'number'
         ? product.calculated_outbound_volume_num
         : (parseFloat(product.spu_unit_num) || 0);
      
      totalOutboundVolume += volume;
      
      console.log(`产品 ${product.name} 的出库量数值为:`, volume);
   });
   
   // 更新类别的待出库数量显示
   category.pending_outbound = totalOutboundVolume;
   category.pending_outbound_display = `${totalOutboundVolume.toFixed(2)}${totalOutboundUnit}`;
   
   console.log(`SPU类别 ${category.category} 待出库更新:`, {
      总出库量: totalOutboundVolume,
      单位: totalOutboundUnit,
      显示: category.pending_outbound_display
   });
};

// 统一出库量显示逻辑
const getOutboundVolumeDisplay = (product: any): string => {
   // 1. 优先显示实时计算的出库量（用户修改数量后的结果）
   if (product.calculated_outbound_display) {
      return product.calculated_outbound_display;
   }
   
   // 2. 编辑模式下显示后端回显的出库量
   if (form.value.id && product.outbound_display) {
      return product.outbound_display;
   }
   
   // 3. 降级到默认计算方式（例如，新增时或数量为0时）
   return '0' + (product.spu_unit_name || '');
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
   --el-dialog-padding-primary: 0px;
}

::v-deep(.el-dialog) {
  margin-top: 40px !important;
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
}

::v-deep .el-dialog__header {
   padding: 10px 16px;
   border-bottom: 1px solid #f0f0f0;
   font-weight: bold;
}

::v-deep .dialog-footer {
   padding: 10px 16px;
   border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
   color: #000;
}

// ::v-deep .el-dialog__body {
//    padding: 10px 10px;
// }

/* 2. 表头、表尾固定高，body 吃剩余 */
::v-deep(.el-dialog__body) {
  flex: 1;
  overflow-x: auto;   /* 需要横向时允许滚 */
  overflow-y: hidden; /* 纵向交给 el-table 内部 */
  padding: 10px;
}

:deep(.el-form-item__label) {
   justify-content: flex-start;
}

:deep(.el-form-item) {
   flex-direction: column;
   margin-bottom: 7px;
}

:deep(.el-select__wrapper) {
   background: #fafcfb;
}

:deep(.el-badge__content.is-fixed) {
   color: #666;
   border-radius: 3px;
   padding: 4px;
}

:deep(.el-table .cell) {
   display: flex;
   justify-content: center;
}

:deep(.el-button:hover) {
   color: #6860ff;
   background: #f4f5f7;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
   width: 100%;
}

:deep(.el-input__wrapper:hover) {
   box-shadow: inset 0 0 0 1px #6860ff;
}

.supply-products {

   display: flex;
   flex-direction: column;
   height: 100%;    

   .table-box {
      flex: 1;             /* 剩余高全给表格 */
      overflow: auto;      /* 纵向超出自己滚 */
      min-height: 0;       /* 防止 flex 子项被内容撑爆 */
   }
   .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      font-weight: bold;

      .title-text {
         display: flex;
         align-items: center;

         .line {
            height: 17px;
            width: 2px;
            border-radius: 12px;
            margin-right: 8px;
            background-color: #6860ff;
         }
      }
   }
}

.image-list {
   display: flex;
   gap: 8px;

   .el-image {
      width: 40px;
      height: 40px;
      border-radius: 4px;
   }
}

.total-info {
   margin-top: 16px;
   padding: 12px 16px;
   background-color: #f8f9fa;
   border-radius: 4px;
   border: 1px solid #e9ecef;

   .total-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      color: #495057;

      span {
         &:last-child {
            color: #626aef;
            font-weight: 600;
         }
      }
   }
}

// 树形表格相关样式
.category-name {
   display: flex;
   align-items: center;
   font-weight: 600;
   color: #2c3e50;

   .category-icon {
      margin-right: 8px;
      color: #626aef;
   }
}

// 库存状态标签样式
.stock-normal {
   background-color: #f0f9ff;
   color: #10b981;
   border-color: #10b981;
}

.stock-low {
   background-color: #fef3c7;
   color: #f59e0b;
   border-color: #f59e0b;
}

.stock-empty {
   background-color: #fee2e2;
   color: #ef4444;
   border-color: #ef4444;
}

// 树形表格行样式
:deep(.el-table__expand-icon) {
   color: #626aef;
}

:deep(.el-table__row--level-0) {
   background-color: #fafbfc;
}

:deep(.el-table__row--level-1) {
   background-color: #ffffff;
}

:deep(.el-table__row--level-0:hover) {
   background-color: #f0f2f5 !important;
}

:deep(.el-table__row--level-1:hover) {
   background-color: #f8f9fa !important;
}

</style>